package com.pricl.frame.core.web;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.pricl.frame.core.E;
import com.pricl.frame.core.R;

/**
 * <p>
 * 异常页面处理 记录异常日志
 * </p>
 *
 */
public class MyMappingExceptionResolver extends SimpleMappingExceptionResolver {

	Logger logger = LoggerFactory.getLogger(MyMappingExceptionResolver.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		logger.error(sw.toString());


		String accept = request.getHeader("Accept");
		boolean isJson = accept != null && accept.indexOf("application/json") != -1
				|| request.getAttribute("reponseJson") != null;
		if (isJson) {
			applyStatusCodeIfPossible(request, response, 200);

			ModelAndView mav = new ModelAndView();
			MappingJackson2JsonView view = new MappingJackson2JsonView();
			Map<String, Object> attr = new HashMap<>();

			// 使用硬编码？？？
			// Class<? extends R> clazz = r.getClass();
			// Field[] fields = clazz.getDeclaredFields();
			// for (Field field : fields) {
			// try {
			// PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
			// clazz);
			// Method getMethod = pd.getReadMethod();
			// attr.put(field.getName(), getMethod.invoke(r));
			// } catch (IntrospectionException e) {
			// e.printStackTrace();
			// } catch (IllegalAccessException e) {
			// e.printStackTrace();
			// } catch (IllegalArgumentException e) {
			// e.printStackTrace();
			// } catch (InvocationTargetException e) {
			// e.printStackTrace();
			// }
			//
			// }
			// TODO 与上段代码功能相同 硬编码
			if (ex instanceof E) {
				E e = (E) ex;
				attr.put("code", e.code);
				attr.put("data", e.data);
			}

//			attr.put("code", r.code);
//			attr.put("data", r.data);
//			attr.put("msg", r.msg);

			view.setAttributesMap(attr);
			mav.setView(view);
			return mav;
			// return null;

		}
		R r = R.exception(ex);
		String viewName = determineViewName(ex, request);
		if (viewName != null) {
			applyStatusCodeIfPossible(request, response, 200);

			ModelAndView mav = getModelAndView(viewName, ex, request);
			mav.addObject("r", r);
			return mav;
		} else {
			return null;
		}
	}

}
